﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Reflection;

namespace DevFx.FrameWork
{
    public class LinqHelper
    {

        /// <summary>
        /// 分页数据排序
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source">数据源</param>
        /// <param name="condition">分页排序条件</param>
        /// <returns></returns>
        public static IQueryable<T> DataSorting<T>(IQueryable<T> source, PagerCondition Pager)
        {
            Expression expr = source.Expression;
            string methodAsc = "OrderBy";
            string methodDesc = "OrderByDescending";
            foreach (SortCondition Scon in Pager.SortConditions)
            {
                Type[] types = new Type[2];
                string cons = Scon.SortField;
                string sortDirection = Scon.SortDirection.ToString();
                ParameterExpression param = Expression.Parameter(typeof(T), Scon.SortField);
                PropertyInfo pi = typeof(T).GetProperty(Scon.SortField);
                types[0] = typeof(T);
                types[1] = pi.PropertyType;
                string sortingDir = sortDirection.ToUpper().Trim() == "ASC" ? methodAsc : methodDesc;
                //expr = Expression.Call(typeof(Queryable), sortingDir, types, source.Expression, Expression.Lambda(Expression.Property(param, cons), param));
                expr = Expression.Call(typeof(Queryable), sortingDir, types, expr, Expression.Lambda(Expression.Property(param, cons), param));
                methodAsc = "ThenBy";
                methodDesc = "ThenByDescending";
            }
            Pager.SortConditions.Clear();
            IQueryable<T> query = source.AsQueryable().Provider.CreateQuery<T>(expr);
            return query;
        }


        /// <summary>
        /// 数据分页
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public static IQueryable<T> DataPaging<T>(IQueryable<T> source, PagerCondition Pager)
        {
            if (Pager.IsPaging)
            {
                return source.Skip((Pager.CurrentPage - 1) * Pager.PageSize).Take(Pager.PageSize);
            }
            return source;
        }
        /// <summary>
        /// 数据分页排序
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public static IQueryable<T> SortingAndPaging<T>(IQueryable<T> source, PagerCondition Pager)
        {
            Pager.RecordCount = source.Count();
            IQueryable<T> query = DataSorting<T>(source, Pager);
            return DataPaging(query, Pager);
        }


    }
}
    